/* URBAN EXPLORER PROJECT
 * 
 * Author: Karthick Nanmaran (s1051713), School of Informatics, The University of Edinburgh
 * Email: karthicknanmaran@gmail.com
 * 
 * Supervisor: Dr.William Mackaness, 
 * 			   Institute of Geography,
 * 			   School of GeoSciences,
 * 			   The University of Edinburgh.
 * Email: william.mackaness@ed.ac.uk
 * 
 * This code can be found online at http://code.google.com/p/urban-explorers/
*/
package Firstdroid.Gps;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;

public class SVRTS extends Activity implements OnClickListener,OnInitListener {
    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
    private ListView mList;

    private Button speakBtn = null;
    private static final int REQ_TTS_STATUS_CHECK = 0;
    private static final String TAG = "TTS Demo";
    private TextToSpeech Tts;
    private Button mAgainButton;
    private EditText inputText;
	private Button clickspeakButton;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voice);

        // Button and ListView for Voice Recognition
        Button speakButton = (Button) findViewById(R.id.btn_speak);
        mList = (ListView) findViewById(R.id.list);

        //Button for Text to Speech. Speaks preset Text messages
        speakBtn = (Button)findViewById(R.id.speak);

        inputText = (EditText) findViewById(R.id.input_text);
        clickspeakButton = (Button) findViewById(R.id.clicktospeak);
        
        clickspeakButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				String text = inputText.getText().toString();
				if (text!=null && text.length()>0) {
					Toast.makeText(SVRTS.this, "Saying: " + text, Toast.LENGTH_LONG).show();
					Tts.speak(text, TextToSpeech.QUEUE_ADD, null);
				}
			}
		});
        // Check to see if a recognition activity is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() != 0) {
            speakButton.setOnClickListener(this);
        } else {
            speakButton.setEnabled(false);
            speakButton.setText("Recognizer not present");
        }

        // Check to be sure that TTS exists and is okay to use
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, REQ_TTS_STATUS_CHECK);
        
     // Initialize text-to-speech. This is an asynchronous operation.
        // The OnInitListener (second argument) is called after initialization completes.
        Tts = new TextToSpeech(this,
            this  // TextToSpeech.OnInitListener
            );

        // The button is disabled in the layout.
        // It will be enabled upon initialization of the TTS engine.
        mAgainButton = (Button) findViewById(R.id.speak);

        mAgainButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                sayHello();
            }
        });        
    }
        //Handle the click on the start recognition button and on text to speech button
        public void onClick(View v) {

        switch (v.getId()) {
        case R.id.btn_speak:
            startVoiceRecognitionActivity();
            break;
        case R.id.speak:
            Tts.speak(mList.toString(), TextToSpeech.QUEUE_ADD, null);
            break;
        case R.id.clicktospeak:
        {
        	String text = inputText.getText().toString();
			if (text!=null && text.length()>0) {
				Toast.makeText(SVRTS.this, "Laura: " + text, Toast.LENGTH_LONG).show();
				Tts.speak(text, TextToSpeech.QUEUE_ADD, null);
				Tts.speak(text,TextToSpeech.QUEUE_FLUSH,null);
			}
			break;
        }	
        }
        }

        //Fire an intent to start the speech recognition activity
        private void startVoiceRecognitionActivity() {
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Recognizing Speech");
            startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
        }

        // Handle the results 
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
                // Fill the list view with the strings the recognizer thought it could have heard
                ArrayList<String> matches = data.getStringArrayListExtra(
                        RecognizerIntent.EXTRA_RESULTS);
                mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                        matches));
            }

            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == REQ_TTS_STATUS_CHECK) {
                switch (resultCode) {
                case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
                    // TTS is up and running
                    Tts = new TextToSpeech(this, this);
                    Log.v(TAG, "SVOX Pico Engine is installed and okay");
                    break;
                case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
                case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
                case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
                    // missing data, install it
                    Log.v(TAG, "Need language stuff: " + resultCode);
                    Intent installIntent = new Intent();
                    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                    startActivity(installIntent);
                    break;
                case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
                default:
                    Log.e(TAG, "Got a failure. TTS is not available");
                }
            }
            else {
                // Got something else
            }

        }

         @Override
            public void onInit(int status) {
                // TTS engine is ready, and so the button is enabled
                if( status == TextToSpeech.SUCCESS) {
                    speakBtn.setEnabled(true);
                 // Set preferred language to UK English.
                    int result = Tts.setLanguage(Locale.UK);
                    if (result == TextToSpeech.LANG_MISSING_DATA ||
                        result == TextToSpeech.LANG_NOT_SUPPORTED) {
                       // Lanuage data is missing or the language is not supported.
                        Log.e(TAG, "Language is not available.");
                    } else {
                        // The TTS engine has been successfully initialized.
                        // Allow the user to press the button for the app to speak again.
                        mAgainButton.setEnabled(true);
                        // Greet the user.
                        sayHello();
                    }
                }
                else {
                    // Initialization failed.
                    Log.e(TAG, "Could not initialize TextToSpeech.");
                }
            }
         private static final Random RANDOM = new Random();
         private static final String[] HELLOS = {
           "Hey Everyone! My name is Laura! I am a simple Text to Speech Engine! I was created by car-thick!",
           "Hello William? How are you?",
           "Hello there! Wats-up?"
         };

         private void sayHello() {
             // Select a random hello.
             int helloLength = HELLOS.length;
             String hello = HELLOS[RANDOM.nextInt(helloLength)];
             Tts.speak(hello,
                 TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
                 null);
         }
            @Override
            public void onPause()
            {
                super.onPause();
                if( Tts != null)
                    Tts.stop();
            }
            @Override
            public void onDestroy()
            {
            	if (Tts != null) {
                    Tts.stop();
                    Tts.shutdown();
                }
                super.onDestroy();
            }
}
